/*  
 * 项目名: YYS 
 * 文件名: MediaPlayActivity.java  
 * 版权声明:
 *      本系统的所有内容，包括源码、页面设计，文字、图像以及其他任何信息，
 *      如未经特殊说明，其版权均属大华技术股份有限公司所有。
 *      Copyright (c) 2015 大华技术股份有限公司
 *      版权所有
 */
package com.haierCamera.customapplication.ui.mediaplay;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.business.util.PermissionHelper;
import com.haierCamera.customapplication.ui.main.HZKLCameraDeviceDetailActivity;
import com.haierCamera.customapplication.ui.main.HZKLMsgAlarmSettingActivity;
import com.haierCamera.customapplication.ui.main.HZKLRecordListAllActivity;
import com.haierCamera.customapplication.ui.main.common.CommonTitle;
import com.haierCamera.customapplication.ui.main.widget.DialogEditDevice;
import com.haierCamera.customapplication.ui.mediaplay.fragment.MediaPlayBackFragment;
import com.haierCamera.customapplication.ui.mediaplay.fragment.MediaPlayFragment;
import com.haierCamera.customapplication.ui.mediaplay.fragment.MediaPlayOnlineFragment;
import com.haierCamera.customapplication.ui.user.activity.HZKLRepairActivity;
import com.haierCamera.customapplication.utils.DensityUtil;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

/**
 * 描述：视频播放Activity 作者： lc
 */
public class MediaPlayActivity extends FragmentActivity implements
        MediaPlayFragment.BackHandlerInterface,
        ActivityCompat.OnRequestPermissionsResultCallback {

    private final static String tag = "MediaPlayActivity";
    private CommonTitle mCommonTitle;
    private MediaPlayFragment mMediaPlayFragment;

    public static final int IS_VIDEO_ONLINE = 1;
    public static final int IS_VIDEO_REMOTE_RECORD = 2;
    public static final int IS_VIDEO_REMOTE_CLOUD_RECORD = 3;

    private ProgressDialog mLoadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hzkl_activity_media_video);
        // 绘制标题
        mCommonTitle = (CommonTitle) findViewById(R.id.title);
        mCommonTitle.initView(R.drawable.hzkl_title_btn_back, 0, getIntent()
                .getIntExtra("MEDIA_TITLE", 0));
//        mCommonTitle.setIdRight2(R.drawable.hzkl_camera_file);


        PermissionHelper.requestPermission(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO});
        // 嵌入使用的帧
        MediaPlayFragment mediaPlayFragment; // 引用的布局帧
        Bundle b = new Bundle();
        String resId; // 资源id号
        Log.i("TAG","changeFragment-" + getIntent().getIntExtra("TYPE", 0));
        switch (getIntent().getIntExtra("TYPE", 0)) {
            case IS_VIDEO_ONLINE:
                mCommonTitle.setTitleRightView(R.drawable.hzkl_camera_video_edit);
                mCommonTitle.setTitleCenterText("" + getIntent().getStringExtra("RESNAME")
                        ,R.color.hzkl_text_color_dark
                        , R.dimen.hzkl_14dp);
                mCommonTitle.setTitleRight2View(0);
                mCommonTitle.setOnTitleClickListener(new CommonTitle.OnTitleClickListener() {
                    @Override
                    public void onCommonTitleClick(int id) {
                        // TODO Auto-generated method stub
                        switch (id) {
                            case CommonTitle.ID_LEFT:
                                finish();
                                break;
                            case CommonTitle.ID_RIGHT:
//                                startActivityForResult(new Intent(MediaPlayActivity.this
//                                        , HZKLCameraDeviceDetailActivity.class)
//                                        .putExtra("accountDeviceId",getIntent().getStringExtra("RESACCOUNTDEVICEID"))
//                                        .putExtra("name",getIntent().getStringExtra("RESNAME"))
//                                        .putExtra("sn",getIntent().getStringExtra("RESDEVICEID"))
//                                        .putExtra("sc",getIntent().getStringExtra("RESPWD"))
//                                        .putExtra("picture",getIntent().getStringExtra("RESPICTURE"))
//                                        ,1000);

                                new DialogEditDevice(MediaPlayActivity.this)
                                        .setListener(new DialogEditDevice.OnSelectedListener() {
                                    @Override
                                    public void click(int type) {
                                        switch (type) {
                                            case 0:
                                                startActivity(new Intent(MediaPlayActivity.this
                                                        , HZKLMsgAlarmSettingActivity.class)
                                                        .putExtra("devId",getIntent().getStringExtra("RESDEVICEID")));
                                                break;
                                            case 1:
                                                startActivity(new Intent(MediaPlayActivity.this
                                                        , HZKLRecordListAllActivity.class)
                                                        .putExtra("name",getIntent().getStringExtra("RESNAME"))
                                                        .putExtra("devId",getIntent().getStringExtra("RESDEVICEID"))
                                                        .putExtra("cameraPwd",getIntent().getStringExtra("RESPWD")));

                                                break;
                                            case 2:
                                                startActivityForResult(new Intent(MediaPlayActivity.this
                                                        ,HZKLCameraDeviceDetailActivity.class)
                                                        .putExtra("accountDeviceId",getIntent().getStringExtra("RESACCOUNTDEVICEID"))
                                                        .putExtra("name",getIntent().getStringExtra("RESNAME"))
                                                        .putExtra("sn",getIntent().getStringExtra("RESDEVICEID"))
                                                        .putExtra("sc",getIntent().getStringExtra("RESPWD"))
                                                                .putExtra("ability",getIntent().getStringExtra("RESABILITY"))
                                                        .putExtra("picture",getIntent().getStringExtra("RESPICTURE"))
                                                        ,10001);
                                                break;
                                            case 3:
                                                startActivity(new Intent(MediaPlayActivity.this
                                                        , HZKLRepairActivity.class)
                                                        .putExtra("deviceId",getIntent().getStringExtra("RESDEVICEID")));
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                }).showDialog();
                                break;
                            default:
                                break;
                        }
                    }
                });
                mediaPlayFragment = new MediaPlayOnlineFragment();
//                resId = getIntent().getStringExtra("UUID");
//                b.putString("RESID", resId);
                b.putString("RESID", getIntent().getStringExtra("UUID"));
                b.putString("RESDEVICEID", getIntent().getStringExtra("RESDEVICEID"));
                b.putString("RESPWD", getIntent().getStringExtra("RESPWD"));
                b.putString("RESPWD", getIntent().getStringExtra("RESPWD"));
                b.putString("RESABILITY", getIntent().getStringExtra("RESABILITY"));
                b.putIntegerArrayList("RESCHANNELS", getIntent().getIntegerArrayListExtra("RESCHANNELS"));
                mediaPlayFragment.setArguments(b);
                changeFragment(mediaPlayFragment, false);
                break;
            case IS_VIDEO_REMOTE_RECORD:
//                mCommonTitle.setTitleCenterText("" + getIntent().getStringExtra("RESNAME")
//                        ,R.color.hzkl_text_color_dark
//                        , R.dimen.hzkl_14dp);
                mCommonTitle.setTitleRight2View(1);
                mCommonTitle.setOnTitleClickListener(new CommonTitle.OnTitleClickListener() {
                    @Override
                    public void onCommonTitleClick(int id) {
                        // TODO Auto-generated method stub
                        switch (id) {
                            case CommonTitle.ID_LEFT:
                                finish();
                                break;
                                case CommonTitle.ID_RIGHT_2:
                                    getDeviceChannel(getIntent().getStringExtra("RESDEVICEID")
                                            ,getIntent().getStringExtra("RESPWD"));
                                    break;
                            default:
                                break;
                        }
                    }
                });
                mediaPlayFragment = new MediaPlayBackFragment();
                resId = getIntent().getStringExtra("RESID");
                b.putString("RESID", resId);
                b.putInt("RESCHANNELID", getIntent().getIntExtra("RESCHANNELID",0));
                b.putString("RESDEVICEID", getIntent().getStringExtra("RESDEVICEID"));
                b.putString("RESPWD", getIntent().getStringExtra("RESPWD"));
                mediaPlayFragment.setArguments(b);
                changeFragment(mediaPlayFragment, false);
                break;
            case IS_VIDEO_REMOTE_CLOUD_RECORD://云录像播放
                mediaPlayFragment = new MediaPlayBackFragment();
                resId = getIntent().getStringExtra("ID");
                b.putString("RESID", resId);
                mediaPlayFragment.setArguments(b);
                changeFragment(mediaPlayFragment, false);
                break;
            default:
                break;
        }

        mLoadingDialog = new ProgressDialog(this);
        mLoadingDialog.setMessage("请稍后");
    }

    public void showLoadingDialog() {
        if (null == mLoadingDialog) {
            return;
        }
        mLoadingDialog.setCanceledOnTouchOutside(true);
        mLoadingDialog.show();
    }

    public void showLoadingDialog(String message) {
        if (null == mLoadingDialog) {
            return;
        }
        mLoadingDialog.setMessage(message);
        mLoadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (null == mLoadingDialog) {
            return;
        }
        mLoadingDialog.dismiss();
    }

    private void getDeviceChannel(String sn ,String sc){
        showLoadingDialog();
        Business.getInstance().getDeviceInfo2(sn,new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    Log.i("TAG","size-" + ((Bundle) msg.obj).getIntegerArrayList("list").size());

                    for (int j = 0; j < ((Bundle) msg.obj).getIntegerArrayList("list").size(); j++) {
                        Log.i("TAG","getDeviceChannel-" + ((Bundle) msg.obj).getIntegerArrayList("list").get(j));
                    }
                    dismissLoadingDialog();
                    startActivity(new Intent(MediaPlayActivity.this, MediaPlayActivity.class)
                            .putExtra("TYPE", 1)
                            .putExtra("RESID", "0")
                            .putExtra("RESDEVICEID", sn)
                            .putExtra("RESPWD", sc)
                            .putExtra("RESNAME", getIntent().getStringExtra("RESNAME"))
                            .putExtra("RESCHANNELS", ((Bundle) msg.obj).getIntegerArrayList("list")));
                }

            }
        });
    }

    /**
     * @see com.mm.android.yys.common.MainControllerListener#changeFragment(com.mm.android.commonlib.base.BaseFragment,
     * boolean) 描述：切换fragment
     */
    public void changeFragment(Fragment targetFragment, boolean isAddToStack) {
        if (isAddToStack) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.frame_content, targetFragment)
                    .addToBackStack(null).commitAllowingStateLoss();
        } else {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.frame_content, targetFragment)
                    .commitAllowingStateLoss();
        }

    }

    @Override
    public void onBackPressed() {
        if (mMediaPlayFragment == null || !mMediaPlayFragment.onBackPressed()) {
            Log.d(tag, "onBackPressed");
            super.onBackPressed();
        }
    }

    @Override
    public void setSelectedFragment(MediaPlayFragment backHandledFragment) {
        // TODO Auto-generated method stub
        this.mMediaPlayFragment = backHandledFragment;
    }

    // 横竖屏切换需要,隐藏标题栏
    public void toggleTitle(boolean isShow) {
        mCommonTitle.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        Log.i("TAG","newConfig.orientation-" + newConfig.orientation);
//        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
////            Toast.makeText(getApplicationContext(), "横屏", Toast.LENGTH_SHORT).show();
//            Log.i("TAG","横屏");
//        }else{
////            Toast.makeText(getApplicationContext(), "竖屏", Toast.LENGTH_SHORT).show();
//            Log.i("TAG","竖屏");
//        }
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//		if (grantResults.length == 1
//				&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
//		} else {
//			Toast.makeText(this, R.string.no_access_write_external_storage,
//					Toast.LENGTH_SHORT).show();
//		}

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1000) {
                finish();
            } else if (requestCode == 10001) {
                finish();
            }
        }
    }
}